Make DB snapshot commit errors include active methods
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28
29 /**
30 * Database abstraction object
31 * @ingroup Database
32 */
33 abstract class DatabaseBase implements IDatabase, LoggerAwareInterface {
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES = 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX = 1500000;
40
41 /** How long before it is worth doing a dummy query to test the connection */
42 const PING_TTL = 1.0;
43 const PING_QUERY = 'SELECT 1 AS ping';
44
45 const TINY_WRITE_SEC = .010;
46 const SLOW_WRITE_SEC = .500;
47 const SMALL_WRITE_ROWS = 100;
48
49 /** @var string SQL query */
50 protected $mLastQuery = '';
51 /** @var bool */
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
55 /** @var string */
56 protected $mServer;
57 /** @var string */
58 protected $mUser;
59 /** @var string */
60 protected $mPassword;
61 /** @var string */
62 protected $mDBname;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
65 /** @var bool */
66 protected $cliMode;
67
68 /** @var BagOStuff APC cache */
69 protected $srvCache;
70 /** @var LoggerInterface */
71 protected $connLogger;
72 /** @var LoggerInterface */
73 protected $queryLogger;
74 /** @var callback Error logging callback */
75 protected $errorLogger;
76
77 /** @var resource Database connection */
78 protected $mConn = null;
79 /** @var bool */
80 protected $mOpened = false;
81
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxIdleCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxPreCommitCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxEndCallbacks = [];
88 /** @var callable[] Map of (name => callable) */
89 protected $mTrxRecurringCallbacks = [];
90 /** @var bool Whether to suppress triggering of transaction end callbacks */
91 protected $mTrxEndCallbacksSuppressed = false;
92
93 /** @var string */
94 protected $mTablePrefix;
95 /** @var string */
96 protected $mSchema;
97 /** @var integer */
98 protected $mFlags;
99 /** @var array */
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
105 /** @var array */
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
111 /** @var string */
112 protected $delimiter = ';';
113
114 /**
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
117 *
118 * @var int
119 */
120 protected $mTrxLevel = 0;
121 /**
122 * Either a short hexidecimal string if a transaction is active or ""
123 *
124 * @var string
125 * @see DatabaseBase::mTrxLevel
126 */
127 protected $mTrxShortId = '';
128 /**
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
132 *
133 * @var float|null
134 * @see DatabaseBase::mTrxLevel
135 */
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
139 /**
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
142 *
143 * @var string
144 * @see DatabaseBase::mTrxLevel
145 */
146 private $mTrxFname = null;
147 /**
148 * Record if possible write queries were done in the last transaction started
149 *
150 * @var bool
151 * @see DatabaseBase::mTrxLevel
152 */
153 private $mTrxDoneWrites = false;
154 /**
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
156 *
157 * @var bool
158 * @see DatabaseBase::mTrxLevel
159 */
160 private $mTrxAutomatic = false;
161 /**
162 * Array of levels of atomicity within transactions
163 *
164 * @var array
165 */
166 private $mTrxAtomicLevels = [];
167 /**
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
169 *
170 * @var bool
171 */
172 private $mTrxAutomaticAtomic = false;
173 /**
174 * Track the write query callers of the current transaction
175 *
176 * @var string[]
177 */
178 private $mTrxWriteCallers = [];
179 /**
180 * @var float Seconds spent in write queries for the current transaction
181 */
182 private $mTrxWriteDuration = 0.0;
183 /**
184 * @var integer Number of write queries for the current transaction
185 */
186 private $mTrxWriteQueryCount = 0;
187 /**
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
189 */
190 private $mTrxWriteAdjDuration = 0.0;
191 /**
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
193 */
194 private $mTrxWriteAdjQueryCount = 0;
195 /**
196 * @var float RTT time estimate
197 */
198 private $mRTTEstimate = 0.0;
199
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
202
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
205
206 /**
207 * @since 1.21
208 * @var resource File handle for upgrade
209 */
210 protected $fileHandle = null;
211
212 /**
213 * @since 1.22
214 * @var string[] Process cache of VIEWs names in the database
215 */
216 protected $allViews = null;
217
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
220
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
223
224 /** @var Profiler */
225 protected $profiler;
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
228
229 /**
230 * Constructor.
231 *
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
235 *
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
238 *
239 * @param array $params Parameters passed from DatabaseBase::factory()
240 */
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
246 $flags = $params['flags'];
247
248 $this->mSchema = $params['schema'];
249 $this->mTablePrefix = $params['tablePrefix'];
250
251 $this->cliMode = isset( $params['cliMode'] )
252 ? $params['cliMode']
253 : ( PHP_SAPI === 'cli' );
254
255 $this->mFlags = $flags;
256 if ( $this->mFlags & DBO_DEFAULT ) {
257 if ( $this->cliMode ) {
258 $this->mFlags &= ~DBO_TRX;
259 } else {
260 $this->mFlags |= DBO_TRX;
261 }
262 }
263
264 $this->mSessionVars = $params['variables'];
265
266 $this->srvCache = isset( $params['srvCache'] )
267 ? $params['srvCache']
268 : new HashBagOStuff();
269
270 $this->profiler = isset( $params['profiler'] )
271 ? $params['profiler']
272 : Profiler::instance(); // @TODO: remove global state
273 $this->trxProfiler = isset( $params['trxProfiler'] )
274 ? $params['trxProfiler']
275 : new TransactionProfiler();
276 $this->connLogger = isset( $params['connLogger'] )
277 ? $params['connLogger']
278 : new \Psr\Log\NullLogger();
279 $this->queryLogger = isset( $params['queryLogger'] )
280 ? $params['queryLogger']
281 : new \Psr\Log\NullLogger();
282
283 if ( $user ) {
284 $this->open( $server, $user, $password, $dbName );
285 }
286 }
287
288 /**
289 * Given a DB type, construct the name of the appropriate child class of
290 * IDatabase. This is designed to replace all of the manual stuff like:
291 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
292 * as well as validate against the canonical list of DB types we have
293 *
294 * This factory function is mostly useful for when you need to connect to a
295 * database other than the MediaWiki default (such as for external auth,
296 * an extension, et cetera). Do not use this to connect to the MediaWiki
297 * database. Example uses in core:
298 * @see LoadBalancer::reallyOpenConnection()
299 * @see ForeignDBRepo::getMasterDB()
300 * @see WebInstallerDBConnect::execute()
301 *
302 * @since 1.18
303 *
304 * @param string $dbType A possible DB type
305 * @param array $p An array of options to pass to the constructor.
306 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
307 * @return IDatabase|null If the database driver or extension cannot be found
308 * @throws InvalidArgumentException If the database driver or extension cannot be found
309 */
310 final public static function factory( $dbType, $p = [] ) {
311 global $wgCommandLineMode;
312
313 $canonicalDBTypes = [
314 'mysql' => [ 'mysqli', 'mysql' ],
315 'postgres' => [],
316 'sqlite' => [],
317 'oracle' => [],
318 'mssql' => [],
319 ];
320
321 $driver = false;
322 $dbType = strtolower( $dbType );
323 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
324 $possibleDrivers = $canonicalDBTypes[$dbType];
325 if ( !empty( $p['driver'] ) ) {
326 if ( in_array( $p['driver'], $possibleDrivers ) ) {
327 $driver = $p['driver'];
328 } else {
329 throw new InvalidArgumentException( __METHOD__ .
330 " type '$dbType' does not support driver '{$p['driver']}'" );
331 }
332 } else {
333 foreach ( $possibleDrivers as $posDriver ) {
334 if ( extension_loaded( $posDriver ) ) {
335 $driver = $posDriver;
336 break;
337 }
338 }
339 }
340 } else {
341 $driver = $dbType;
342 }
343 if ( $driver === false ) {
344 throw new InvalidArgumentException( __METHOD__ .
345 " no viable database extension found for type '$dbType'" );
346 }
347
348 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
349 // and everything else doesn't use a schema (e.g. null)
350 // Although postgres and oracle support schemas, we don't use them (yet)
351 // to maintain backwards compatibility
352 $defaultSchemas = [
353 'mssql' => 'get from global',
354 ];
355
356 $class = 'Database' . ucfirst( $driver );
357 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
358 // Resolve some defaults for b/c
359 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
360 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
361 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
362 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
363 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
364 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
365 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
366 if ( !isset( $p['schema'] ) ) {
367 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
368 }
369 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
370 $p['cliMode'] = $wgCommandLineMode;
371
372 $conn = new $class( $p );
373 if ( isset( $p['connLogger'] ) ) {
374 $conn->connLogger = $p['connLogger'];
375 }
376 if ( isset( $p['queryLogger'] ) ) {
377 $conn->queryLogger = $p['queryLogger'];
378 }
379 if ( isset( $p['errorLogger'] ) ) {
380 $conn->errorLogger = $p['errorLogger'];
381 } else {
382 $conn->errorLogger = [ MWExceptionHandler::class, 'logException' ];
383 }
384 } else {
385 $conn = null;
386 }
387
388 return $conn;
389 }
390
391 public function setLogger( LoggerInterface $logger ) {
392 $this->queryLogger = $logger;
393 }
394
395 public function getServerInfo() {
396 return $this->getServerVersion();
397 }
398
399 /**
400 * @return string Command delimiter used by this database engine
401 */
402 public function getDelimiter() {
403 return $this->delimiter;
404 }
405
406 /**
407 * Boolean, controls output of large amounts of debug information.
408 * @param bool|null $debug
409 * - true to enable debugging
410 * - false to disable debugging
411 * - omitted or null to do nothing
412 *
413 * @return bool|null Previous value of the flag
414 */
415 public function debug( $debug = null ) {
416 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
417 }
418
419 public function bufferResults( $buffer = null ) {
420 if ( is_null( $buffer ) ) {
421 return !(bool)( $this->mFlags & DBO_NOBUFFER );
422 } else {
423 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
424 }
425 }
426
427 /**
428 * Turns on (false) or off (true) the automatic generation and sending
429 * of a "we're sorry, but there has been a database error" page on
430 * database errors. Default is on (false). When turned off, the
431 * code should use lastErrno() and lastError() to handle the
432 * situation as appropriate.
433 *
434 * Do not use this function outside of the Database classes.
435 *
436 * @param null|bool $ignoreErrors
437 * @return bool The previous value of the flag.
438 */
439 protected function ignoreErrors( $ignoreErrors = null ) {
440 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
441 }
442
443 public function trxLevel() {
444 return $this->mTrxLevel;
445 }
446
447 public function trxTimestamp() {
448 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
449 }
450
451 public function tablePrefix( $prefix = null ) {
452 return wfSetVar( $this->mTablePrefix, $prefix );
453 }
454
455 public function dbSchema( $schema = null ) {
456 return wfSetVar( $this->mSchema, $schema );
457 }
458
459 /**
460 * Set the filehandle to copy write statements to.
461 *
462 * @param resource $fh File handle
463 */
464 public function setFileHandle( $fh ) {
465 $this->fileHandle = $fh;
466 }
467
468 public function getLBInfo( $name = null ) {
469 if ( is_null( $name ) ) {
470 return $this->mLBInfo;
471 } else {
472 if ( array_key_exists( $name, $this->mLBInfo ) ) {
473 return $this->mLBInfo[$name];
474 } else {
475 return null;
476 }
477 }
478 }
479
480 public function setLBInfo( $name, $value = null ) {
481 if ( is_null( $value ) ) {
482 $this->mLBInfo = $name;
483 } else {
484 $this->mLBInfo[$name] = $value;
485 }
486 }
487
488 public function setLazyMasterHandle( IDatabase $conn ) {
489 $this->lazyMasterHandle = $conn;
490 }
491
492 /**
493 * @return IDatabase|null
494 * @see setLazyMasterHandle()
495 * @since 1.27
496 */
497 public function getLazyMasterHandle() {
498 return $this->lazyMasterHandle;
499 }
500
501 /**
502 * @param TransactionProfiler $profiler
503 * @since 1.27
504 */
505 public function setTransactionProfiler( TransactionProfiler $profiler ) {
506 $this->trxProfiler = $profiler;
507 }
508
509 /**
510 * Returns true if this database supports (and uses) cascading deletes
511 *
512 * @return bool
513 */
514 public function cascadingDeletes() {
515 return false;
516 }
517
518 /**
519 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
520 *
521 * @return bool
522 */
523 public function cleanupTriggers() {
524 return false;
525 }
526
527 /**
528 * Returns true if this database is strict about what can be put into an IP field.
529 * Specifically, it uses a NULL value instead of an empty string.
530 *
531 * @return bool
532 */
533 public function strictIPs() {
534 return false;
535 }
536
537 /**
538 * Returns true if this database uses timestamps rather than integers
539 *
540 * @return bool
541 */
542 public function realTimestamps() {
543 return false;
544 }
545
546 public function implicitGroupby() {
547 return true;
548 }
549
550 public function implicitOrderby() {
551 return true;
552 }
553
554 /**
555 * Returns true if this database can do a native search on IP columns
556 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
557 *
558 * @return bool
559 */
560 public function searchableIPs() {
561 return false;
562 }
563
564 /**
565 * Returns true if this database can use functional indexes
566 *
567 * @return bool
568 */
569 public function functionalIndexes() {
570 return false;
571 }
572
573 public function lastQuery() {
574 return $this->mLastQuery;
575 }
576
577 public function doneWrites() {
578 return (bool)$this->mDoneWrites;
579 }
580
581 public function lastDoneWrites() {
582 return $this->mDoneWrites ?: false;
583 }
584
585 public function writesPending() {
586 return $this->mTrxLevel && $this->mTrxDoneWrites;
587 }
588
589 public function writesOrCallbacksPending() {
590 return $this->mTrxLevel && (
591 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
592 );
593 }
594
595 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
596 if ( !$this->mTrxLevel ) {
597 return false;
598 } elseif ( !$this->mTrxDoneWrites ) {
599 return 0.0;
600 }
601
602 switch ( $type ) {
603 case self::ESTIMATE_DB_APPLY:
604 $this->ping( $rtt );
605 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
606 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
607 // For omitted queries, make them count as something at least
608 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
609 $applyTime += self::TINY_WRITE_SEC * $omitted;
610
611 return $applyTime;
612 default: // everything
613 return $this->mTrxWriteDuration;
614 }
615 }
616
617 public function pendingWriteCallers() {
618 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
619 }
620
621 protected function pendingWriteAndCallbackCallers() {
622 if ( !$this->mTrxLevel ) {
623 return [];
624 }
625
626 $fnames = $this->mTrxWriteCallers;
627 foreach ( [
628 $this->mTrxIdleCallbacks,
629 $this->mTrxPreCommitCallbacks,
630 $this->mTrxEndCallbacks
631 ] as $callbacks ) {
632 foreach ( $callbacks as $callback ) {
633 $fnames[] = $callback[1];
634 }
635 }
636
637 return $fnames;
638 }
639
640 public function isOpen() {
641 return $this->mOpened;
642 }
643
644 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
645 if ( $remember === self::REMEMBER_PRIOR ) {
646 array_push( $this->priorFlags, $this->mFlags );
647 }
648 $this->mFlags |= $flag;
649 }
650
651 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
652 if ( $remember === self::REMEMBER_PRIOR ) {
653 array_push( $this->priorFlags, $this->mFlags );
654 }
655 $this->mFlags &= ~$flag;
656 }
657
658 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
659 if ( !$this->priorFlags ) {
660 return;
661 }
662
663 if ( $state === self::RESTORE_INITIAL ) {
664 $this->mFlags = reset( $this->priorFlags );
665 $this->priorFlags = [];
666 } else {
667 $this->mFlags = array_pop( $this->priorFlags );
668 }
669 }
670
671 public function getFlag( $flag ) {
672 return !!( $this->mFlags & $flag );
673 }
674
675 public function getProperty( $name ) {
676 return $this->$name;
677 }
678
679 public function getWikiID() {
680 if ( $this->mTablePrefix ) {
681 return "{$this->mDBname}-{$this->mTablePrefix}";
682 } else {
683 return $this->mDBname;
684 }
685 }
686
687 /**
688 * Get information about an index into an object
689 * @param string $table Table name
690 * @param string $index Index name
691 * @param string $fname Calling function name
692 * @return mixed Database-specific index description class or false if the index does not exist
693 */
694 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
695
696 /**
697 * Wrapper for addslashes()
698 *
699 * @param string $s String to be slashed.
700 * @return string Slashed string.
701 */
702 abstract function strencode( $s );
703
704 /**
705 * Called by serialize. Throw an exception when DB connection is serialized.
706 * This causes problems on some database engines because the connection is
707 * not restored on unserialize.
708 */
709 public function __sleep() {
710 throw new RuntimeException( 'Database serialization may cause problems, since ' .
711 'the connection is not restored on wakeup.' );
712 }
713
714 protected function installErrorHandler() {
715 $this->mPHPError = false;
716 $this->htmlErrors = ini_set( 'html_errors', '0' );
717 set_error_handler( [ $this, 'connectionerrorLogger' ] );
718 }
719
720 /**
721 * @return bool|string
722 */
723 protected function restoreErrorHandler() {
724 restore_error_handler();
725 if ( $this->htmlErrors !== false ) {
726 ini_set( 'html_errors', $this->htmlErrors );
727 }
728 if ( $this->mPHPError ) {
729 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
730 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
731
732 return $error;
733 } else {
734 return false;
735 }
736 }
737
738 /**
739 * @param int $errno
740 * @param string $errstr
741 */
742 public function connectionerrorLogger( $errno, $errstr ) {
743 $this->mPHPError = $errstr;
744 }
745
746 /**
747 * Create a log context to pass to PSR logging functions.
748 *
749 * @param array $extras Additional data to add to context
750 * @return array
751 */
752 protected function getLogContext( array $extras = [] ) {
753 return array_merge(
754 [
755 'db_server' => $this->mServer,
756 'db_name' => $this->mDBname,
757 'db_user' => $this->mUser,
758 ],
759 $extras
760 );
761 }
762
763 public function close() {
764 if ( $this->mConn ) {
765 if ( $this->trxLevel() ) {
766 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
767 }
768
769 $closed = $this->closeConnection();
770 $this->mConn = false;
771 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
772 throw new RuntimeException( "Transaction callbacks still pending." );
773 } else {
774 $closed = true;
775 }
776 $this->mOpened = false;
777
778 return $closed;
779 }
780
781 /**
782 * Make sure isOpen() returns true as a sanity check
783 *
784 * @throws DBUnexpectedError
785 */
786 protected function assertOpen() {
787 if ( !$this->isOpen() ) {
788 throw new DBUnexpectedError( $this, "DB connection was already closed." );
789 }
790 }
791
792 /**
793 * Closes underlying database connection
794 * @since 1.20
795 * @return bool Whether connection was closed successfully
796 */
797 abstract protected function closeConnection();
798
799 function reportConnectionError( $error = 'Unknown error' ) {
800 $myError = $this->lastError();
801 if ( $myError ) {
802 $error = $myError;
803 }
804
805 # New method
806 throw new DBConnectionError( $this, $error );
807 }
808
809 /**
810 * The DBMS-dependent part of query()
811 *
812 * @param string $sql SQL query.
813 * @return ResultWrapper|bool Result object to feed to fetchObject,
814 * fetchRow, ...; or false on failure
815 */
816 abstract protected function doQuery( $sql );
817
818 /**
819 * Determine whether a query writes to the DB.
820 * Should return true if unsure.
821 *
822 * @param string $sql
823 * @return bool
824 */
825 protected function isWriteQuery( $sql ) {
826 return !preg_match(
827 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
828 }
829
830 /**
831 * @param $sql
832 * @return string|null
833 */
834 protected function getQueryVerb( $sql ) {
835 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
836 }
837
838 /**
839 * Determine whether a SQL statement is sensitive to isolation level.
840 * A SQL statement is considered transactable if its result could vary
841 * depending on the transaction isolation level. Operational commands
842 * such as 'SET' and 'SHOW' are not considered to be transactable.
843 *
844 * @param string $sql
845 * @return bool
846 */
847 protected function isTransactableQuery( $sql ) {
848 $verb = $this->getQueryVerb( $sql );
849 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
850 }
851
852 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
853 global $wgUser;
854
855 $priorWritesPending = $this->writesOrCallbacksPending();
856 $this->mLastQuery = $sql;
857
858 $isWrite = $this->isWriteQuery( $sql );
859 if ( $isWrite ) {
860 $reason = $this->getReadOnlyReason();
861 if ( $reason !== false ) {
862 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
863 }
864 # Set a flag indicating that writes have been done
865 $this->mDoneWrites = microtime( true );
866 }
867
868 # Add a comment for easy SHOW PROCESSLIST interpretation
869 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
870 $userName = $wgUser->getName();
871 if ( mb_strlen( $userName ) > 15 ) {
872 $userName = mb_substr( $userName, 0, 15 ) . '...';
873 }
874 $userName = str_replace( '/', '', $userName );
875 } else {
876 $userName = '';
877 }
878
879 // Add trace comment to the begin of the sql string, right after the operator.
880 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
881 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
882
883 # Start implicit transactions that wrap the request if DBO_TRX is enabled
884 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX )
885 && $this->isTransactableQuery( $sql )
886 ) {
887 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
888 $this->mTrxAutomatic = true;
889 }
890
891 # Keep track of whether the transaction has write queries pending
892 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
893 $this->mTrxDoneWrites = true;
894 $this->trxProfiler->transactionWritingIn(
895 $this->mServer, $this->mDBname, $this->mTrxShortId );
896 }
897
898 if ( $this->debug() ) {
899 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
900 }
901
902 # Avoid fatals if close() was called
903 $this->assertOpen();
904
905 # Send the query to the server
906 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
907
908 # Try reconnecting if the connection was lost
909 if ( false === $ret && $this->wasErrorReissuable() ) {
910 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
911 # Stash the last error values before anything might clear them
912 $lastError = $this->lastError();
913 $lastErrno = $this->lastErrno();
914 # Update state tracking to reflect transaction loss due to disconnection
915 $this->handleTransactionLoss();
916 if ( $this->reconnect() ) {
917 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
918 $this->connLogger->warning( $msg );
919 $this->queryLogger->warning(
920 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
921
922 if ( !$recoverable ) {
923 # Callers may catch the exception and continue to use the DB
924 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
925 } else {
926 # Should be safe to silently retry the query
927 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
928 }
929 } else {
930 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
931 $this->connLogger->error( $msg );
932 }
933 }
934
935 if ( false === $ret ) {
936 # Deadlocks cause the entire transaction to abort, not just the statement.
937 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
938 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
939 if ( $this->wasDeadlock() ) {
940 if ( $this->explicitTrxActive() || $priorWritesPending ) {
941 $tempIgnore = false; // not recoverable
942 }
943 # Update state tracking to reflect transaction loss
944 $this->handleTransactionLoss();
945 }
946
947 $this->reportQueryError(
948 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
949 }
950
951 $res = $this->resultObject( $ret );
952
953 return $res;
954 }
955
956 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
957 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
958 # generalizeSQL() will probably cut down the query to reasonable
959 # logging size most of the time. The substr is really just a sanity check.
960 if ( $isMaster ) {
961 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
962 } else {
963 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
964 }
965
966 # Include query transaction state
967 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
968
969 $startTime = microtime( true );
970 $this->profiler->profileIn( $queryProf );
971 $ret = $this->doQuery( $commentedSql );
972 $this->profiler->profileOut( $queryProf );
973 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
974
975 unset( $queryProfSection ); // profile out (if set)
976
977 if ( $ret !== false ) {
978 $this->lastPing = $startTime;
979 if ( $isWrite && $this->mTrxLevel ) {
980 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
981 $this->mTrxWriteCallers[] = $fname;
982 }
983 }
984
985 if ( $sql === self::PING_QUERY ) {
986 $this->mRTTEstimate = $queryRuntime;
987 }
988
989 $this->trxProfiler->recordQueryCompletion(
990 $queryProf, $startTime, $isWrite, $this->affectedRows()
991 );
992 MWDebug::query( $sql, $fname, $isMaster, $queryRuntime );
993
994 return $ret;
995 }
996
997 /**
998 * Update the estimated run-time of a query, not counting large row lock times
999 *
1000 * LoadBalancer can be set to rollback transactions that will create huge replication
1001 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1002 * queries, like inserting a row can take a long time due to row locking. This method
1003 * uses some simple heuristics to discount those cases.
1004 *
1005 * @param string $sql A SQL write query
1006 * @param float $runtime Total runtime, including RTT
1007 */
1008 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1009 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1010 $indicativeOfReplicaRuntime = true;
1011 if ( $runtime > self::SLOW_WRITE_SEC ) {
1012 $verb = $this->getQueryVerb( $sql );
1013 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1014 if ( $verb === 'INSERT' ) {
1015 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1016 } elseif ( $verb === 'REPLACE' ) {
1017 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1018 }
1019 }
1020
1021 $this->mTrxWriteDuration += $runtime;
1022 $this->mTrxWriteQueryCount += 1;
1023 if ( $indicativeOfReplicaRuntime ) {
1024 $this->mTrxWriteAdjDuration += $runtime;
1025 $this->mTrxWriteAdjQueryCount += 1;
1026 }
1027 }
1028
1029 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1030 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1031 # Dropped connections also mean that named locks are automatically released.
1032 # Only allow error suppression in autocommit mode or when the lost transaction
1033 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1034 if ( $this->mNamedLocksHeld ) {
1035 return false; // possible critical section violation
1036 } elseif ( $sql === 'COMMIT' ) {
1037 return !$priorWritesPending; // nothing written anyway? (T127428)
1038 } elseif ( $sql === 'ROLLBACK' ) {
1039 return true; // transaction lost...which is also what was requested :)
1040 } elseif ( $this->explicitTrxActive() ) {
1041 return false; // don't drop atomocity
1042 } elseif ( $priorWritesPending ) {
1043 return false; // prior writes lost from implicit transaction
1044 }
1045
1046 return true;
1047 }
1048
1049 private function handleTransactionLoss() {
1050 $this->mTrxLevel = 0;
1051 $this->mTrxIdleCallbacks = []; // bug 65263
1052 $this->mTrxPreCommitCallbacks = []; // bug 65263
1053 try {
1054 // Handle callbacks in mTrxEndCallbacks
1055 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1056 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1057 return null;
1058 } catch ( Exception $e ) {
1059 // Already logged; move on...
1060 return $e;
1061 }
1062 }
1063
1064 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1065 if ( $this->ignoreErrors() || $tempIgnore ) {
1066 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1067 } else {
1068 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1069 $this->queryLogger->error(
1070 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1071 $this->getLogContext( [
1072 'method' => __METHOD__,
1073 'errno' => $errno,
1074 'error' => $error,
1075 'sql1line' => $sql1line,
1076 'fname' => $fname,
1077 ] )
1078 );
1079 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1080 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1081 }
1082 }
1083
1084 /**
1085 * Intended to be compatible with the PEAR::DB wrapper functions.
1086 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1087 *
1088 * ? = scalar value, quoted as necessary
1089 * ! = raw SQL bit (a function for instance)
1090 * & = filename; reads the file and inserts as a blob
1091 * (we don't use this though...)
1092 *
1093 * @param string $sql
1094 * @param string $func
1095 *
1096 * @return array
1097 */
1098 protected function prepare( $sql, $func = __METHOD__ ) {
1099 /* MySQL doesn't support prepared statements (yet), so just
1100 * pack up the query for reference. We'll manually replace
1101 * the bits later.
1102 */
1103 return [ 'query' => $sql, 'func' => $func ];
1104 }
1105
1106 /**
1107 * Free a prepared query, generated by prepare().
1108 * @param string $prepared
1109 */
1110 protected function freePrepared( $prepared ) {
1111 /* No-op by default */
1112 }
1113
1114 /**
1115 * Execute a prepared query with the various arguments
1116 * @param string $prepared The prepared sql
1117 * @param mixed $args Either an array here, or put scalars as varargs
1118 *
1119 * @return ResultWrapper
1120 */
1121 public function execute( $prepared, $args = null ) {
1122 if ( !is_array( $args ) ) {
1123 # Pull the var args
1124 $args = func_get_args();
1125 array_shift( $args );
1126 }
1127
1128 $sql = $this->fillPrepared( $prepared['query'], $args );
1129
1130 return $this->query( $sql, $prepared['func'] );
1131 }
1132
1133 /**
1134 * For faking prepared SQL statements on DBs that don't support it directly.
1135 *
1136 * @param string $preparedQuery A 'preparable' SQL statement
1137 * @param array $args Array of Arguments to fill it with
1138 * @return string Executable SQL
1139 */
1140 public function fillPrepared( $preparedQuery, $args ) {
1141 reset( $args );
1142 $this->preparedArgs =& $args;
1143
1144 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1145 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1146 }
1147
1148 /**
1149 * preg_callback func for fillPrepared()
1150 * The arguments should be in $this->preparedArgs and must not be touched
1151 * while we're doing this.
1152 *
1153 * @param array $matches
1154 * @throws DBUnexpectedError
1155 * @return string
1156 */
1157 protected function fillPreparedArg( $matches ) {
1158 switch ( $matches[1] ) {
1159 case '\\?':
1160 return '?';
1161 case '\\!':
1162 return '!';
1163 case '\\&':
1164 return '&';
1165 }
1166
1167 list( /* $n */, $arg ) = each( $this->preparedArgs );
1168
1169 switch ( $matches[1] ) {
1170 case '?':
1171 return $this->addQuotes( $arg );
1172 case '!':
1173 return $arg;
1174 case '&':
1175 # return $this->addQuotes( file_get_contents( $arg ) );
1176 throw new DBUnexpectedError(
1177 $this,
1178 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1179 );
1180 default:
1181 throw new DBUnexpectedError(
1182 $this,
1183 'Received invalid match. This should never happen!'
1184 );
1185 }
1186 }
1187
1188 public function freeResult( $res ) {
1189 }
1190
1191 public function selectField(
1192 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1193 ) {
1194 if ( $var === '*' ) { // sanity
1195 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1196 }
1197
1198 if ( !is_array( $options ) ) {
1199 $options = [ $options ];
1200 }
1201
1202 $options['LIMIT'] = 1;
1203
1204 $res = $this->select( $table, $var, $cond, $fname, $options );
1205 if ( $res === false || !$this->numRows( $res ) ) {
1206 return false;
1207 }
1208
1209 $row = $this->fetchRow( $res );
1210
1211 if ( $row !== false ) {
1212 return reset( $row );
1213 } else {
1214 return false;
1215 }
1216 }
1217
1218 public function selectFieldValues(
1219 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1220 ) {
1221 if ( $var === '*' ) { // sanity
1222 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1223 } elseif ( !is_string( $var ) ) { // sanity
1224 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1225 }
1226
1227 if ( !is_array( $options ) ) {
1228 $options = [ $options ];
1229 }
1230
1231 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1232 if ( $res === false ) {
1233 return false;
1234 }
1235
1236 $values = [];
1237 foreach ( $res as $row ) {
1238 $values[] = $row->$var;
1239 }
1240
1241 return $values;
1242 }
1243
1244 /**
1245 * Returns an optional USE INDEX clause to go after the table, and a
1246 * string to go at the end of the query.
1247 *
1248 * @param array $options Associative array of options to be turned into
1249 * an SQL query, valid keys are listed in the function.
1250 * @return array
1251 * @see DatabaseBase::select()
1252 */
1253 public function makeSelectOptions( $options ) {
1254 $preLimitTail = $postLimitTail = '';
1255 $startOpts = '';
1256
1257 $noKeyOptions = [];
1258
1259 foreach ( $options as $key => $option ) {
1260 if ( is_numeric( $key ) ) {
1261 $noKeyOptions[$option] = true;
1262 }
1263 }
1264
1265 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1266
1267 $preLimitTail .= $this->makeOrderBy( $options );
1268
1269 // if (isset($options['LIMIT'])) {
1270 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1271 // isset($options['OFFSET']) ? $options['OFFSET']
1272 // : false);
1273 // }
1274
1275 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1276 $postLimitTail .= ' FOR UPDATE';
1277 }
1278
1279 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1280 $postLimitTail .= ' LOCK IN SHARE MODE';
1281 }
1282
1283 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1284 $startOpts .= 'DISTINCT';
1285 }
1286
1287 # Various MySQL extensions
1288 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1289 $startOpts .= ' /*! STRAIGHT_JOIN */';
1290 }
1291
1292 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1293 $startOpts .= ' HIGH_PRIORITY';
1294 }
1295
1296 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1297 $startOpts .= ' SQL_BIG_RESULT';
1298 }
1299
1300 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1301 $startOpts .= ' SQL_BUFFER_RESULT';
1302 }
1303
1304 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1305 $startOpts .= ' SQL_SMALL_RESULT';
1306 }
1307
1308 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1309 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1310 }
1311
1312 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1313 $startOpts .= ' SQL_CACHE';
1314 }
1315
1316 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1317 $startOpts .= ' SQL_NO_CACHE';
1318 }
1319
1320 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1321 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1322 } else {
1323 $useIndex = '';
1324 }
1325 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1326 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1327 } else {
1328 $ignoreIndex = '';
1329 }
1330
1331 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1332 }
1333
1334 /**
1335 * Returns an optional GROUP BY with an optional HAVING
1336 *
1337 * @param array $options Associative array of options
1338 * @return string
1339 * @see DatabaseBase::select()
1340 * @since 1.21
1341 */
1342 public function makeGroupByWithHaving( $options ) {
1343 $sql = '';
1344 if ( isset( $options['GROUP BY'] ) ) {
1345 $gb = is_array( $options['GROUP BY'] )
1346 ? implode( ',', $options['GROUP BY'] )
1347 : $options['GROUP BY'];
1348 $sql .= ' GROUP BY ' . $gb;
1349 }
1350 if ( isset( $options['HAVING'] ) ) {
1351 $having = is_array( $options['HAVING'] )
1352 ? $this->makeList( $options['HAVING'], LIST_AND )
1353 : $options['HAVING'];
1354 $sql .= ' HAVING ' . $having;
1355 }
1356
1357 return $sql;
1358 }
1359
1360 /**
1361 * Returns an optional ORDER BY
1362 *
1363 * @param array $options Associative array of options
1364 * @return string
1365 * @see DatabaseBase::select()
1366 * @since 1.21
1367 */
1368 public function makeOrderBy( $options ) {
1369 if ( isset( $options['ORDER BY'] ) ) {
1370 $ob = is_array( $options['ORDER BY'] )
1371 ? implode( ',', $options['ORDER BY'] )
1372 : $options['ORDER BY'];
1373
1374 return ' ORDER BY ' . $ob;
1375 }
1376
1377 return '';
1378 }
1379
1380 // See IDatabase::select for the docs for this function
1381 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1382 $options = [], $join_conds = [] ) {
1383 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1384
1385 return $this->query( $sql, $fname );
1386 }
1387
1388 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1389 $options = [], $join_conds = []
1390 ) {
1391 if ( is_array( $vars ) ) {
1392 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1393 }
1394
1395 $options = (array)$options;
1396 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1397 ? $options['USE INDEX']
1398 : [];
1399 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1400 ? $options['IGNORE INDEX']
1401 : [];
1402
1403 if ( is_array( $table ) ) {
1404 $from = ' FROM ' .
1405 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1406 } elseif ( $table != '' ) {
1407 if ( $table[0] == ' ' ) {
1408 $from = ' FROM ' . $table;
1409 } else {
1410 $from = ' FROM ' .
1411 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1412 }
1413 } else {
1414 $from = '';
1415 }
1416
1417 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1418 $this->makeSelectOptions( $options );
1419
1420 if ( !empty( $conds ) ) {
1421 if ( is_array( $conds ) ) {
1422 $conds = $this->makeList( $conds, LIST_AND );
1423 }
1424 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1425 } else {
1426 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1427 }
1428
1429 if ( isset( $options['LIMIT'] ) ) {
1430 $sql = $this->limitResult( $sql, $options['LIMIT'],
1431 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1432 }
1433 $sql = "$sql $postLimitTail";
1434
1435 if ( isset( $options['EXPLAIN'] ) ) {
1436 $sql = 'EXPLAIN ' . $sql;
1437 }
1438
1439 return $sql;
1440 }
1441
1442 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1443 $options = [], $join_conds = []
1444 ) {
1445 $options = (array)$options;
1446 $options['LIMIT'] = 1;
1447 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1448
1449 if ( $res === false ) {
1450 return false;
1451 }
1452
1453 if ( !$this->numRows( $res ) ) {
1454 return false;
1455 }
1456
1457 $obj = $this->fetchObject( $res );
1458
1459 return $obj;
1460 }
1461
1462 public function estimateRowCount(
1463 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1464 ) {
1465 $rows = 0;
1466 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1467
1468 if ( $res ) {
1469 $row = $this->fetchRow( $res );
1470 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1471 }
1472
1473 return $rows;
1474 }
1475
1476 public function selectRowCount(
1477 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1478 ) {
1479 $rows = 0;
1480 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1481 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1482
1483 if ( $res ) {
1484 $row = $this->fetchRow( $res );
1485 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1486 }
1487
1488 return $rows;
1489 }
1490
1491 /**
1492 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1493 * It's only slightly flawed. Don't use for anything important.
1494 *
1495 * @param string $sql A SQL Query
1496 *
1497 * @return string
1498 */
1499 protected static function generalizeSQL( $sql ) {
1500 # This does the same as the regexp below would do, but in such a way
1501 # as to avoid crashing php on some large strings.
1502 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1503
1504 $sql = str_replace( "\\\\", '', $sql );
1505 $sql = str_replace( "\\'", '', $sql );
1506 $sql = str_replace( "\\\"", '', $sql );
1507 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1508 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1509
1510 # All newlines, tabs, etc replaced by single space
1511 $sql = preg_replace( '/\s+/', ' ', $sql );
1512
1513 # All numbers => N,
1514 # except the ones surrounded by characters, e.g. l10n
1515 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1516 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1517
1518 return $sql;
1519 }
1520
1521 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1522 $info = $this->fieldInfo( $table, $field );
1523
1524 return (bool)$info;
1525 }
1526
1527 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1528 if ( !$this->tableExists( $table ) ) {
1529 return null;
1530 }
1531
1532 $info = $this->indexInfo( $table, $index, $fname );
1533 if ( is_null( $info ) ) {
1534 return null;
1535 } else {
1536 return $info !== false;
1537 }
1538 }
1539
1540 public function tableExists( $table, $fname = __METHOD__ ) {
1541 $table = $this->tableName( $table );
1542 $old = $this->ignoreErrors( true );
1543 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1544 $this->ignoreErrors( $old );
1545
1546 return (bool)$res;
1547 }
1548
1549 public function indexUnique( $table, $index ) {
1550 $indexInfo = $this->indexInfo( $table, $index );
1551
1552 if ( !$indexInfo ) {
1553 return null;
1554 }
1555
1556 return !$indexInfo[0]->Non_unique;
1557 }
1558
1559 /**
1560 * Helper for DatabaseBase::insert().
1561 *
1562 * @param array $options
1563 * @return string
1564 */
1565 protected function makeInsertOptions( $options ) {
1566 return implode( ' ', $options );
1567 }
1568
1569 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1570 # No rows to insert, easy just return now
1571 if ( !count( $a ) ) {
1572 return true;
1573 }
1574
1575 $table = $this->tableName( $table );
1576
1577 if ( !is_array( $options ) ) {
1578 $options = [ $options ];
1579 }
1580
1581 $fh = null;
1582 if ( isset( $options['fileHandle'] ) ) {
1583 $fh = $options['fileHandle'];
1584 }
1585 $options = $this->makeInsertOptions( $options );
1586
1587 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1588 $multi = true;
1589 $keys = array_keys( $a[0] );
1590 } else {
1591 $multi = false;
1592 $keys = array_keys( $a );
1593 }
1594
1595 $sql = 'INSERT ' . $options .
1596 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1597
1598 if ( $multi ) {
1599 $first = true;
1600 foreach ( $a as $row ) {
1601 if ( $first ) {
1602 $first = false;
1603 } else {
1604 $sql .= ',';
1605 }
1606 $sql .= '(' . $this->makeList( $row ) . ')';
1607 }
1608 } else {
1609 $sql .= '(' . $this->makeList( $a ) . ')';
1610 }
1611
1612 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1613 return false;
1614 } elseif ( $fh !== null ) {
1615 return true;
1616 }
1617
1618 return (bool)$this->query( $sql, $fname );
1619 }
1620
1621 /**
1622 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1623 *
1624 * @param array $options
1625 * @return array
1626 */
1627 protected function makeUpdateOptionsArray( $options ) {
1628 if ( !is_array( $options ) ) {
1629 $options = [ $options ];
1630 }
1631
1632 $opts = [];
1633
1634 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1635 $opts[] = $this->lowPriorityOption();
1636 }
1637
1638 if ( in_array( 'IGNORE', $options ) ) {
1639 $opts[] = 'IGNORE';
1640 }
1641
1642 return $opts;
1643 }
1644
1645 /**
1646 * Make UPDATE options for the DatabaseBase::update function
1647 *
1648 * @param array $options The options passed to DatabaseBase::update
1649 * @return string
1650 */
1651 protected function makeUpdateOptions( $options ) {
1652 $opts = $this->makeUpdateOptionsArray( $options );
1653
1654 return implode( ' ', $opts );
1655 }
1656
1657 function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1658 $table = $this->tableName( $table );
1659 $opts = $this->makeUpdateOptions( $options );
1660 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1661
1662 if ( $conds !== [] && $conds !== '*' ) {
1663 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1664 }
1665
1666 return $this->query( $sql, $fname );
1667 }
1668
1669 public function makeList( $a, $mode = LIST_COMMA ) {
1670 if ( !is_array( $a ) ) {
1671 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1672 }
1673
1674 $first = true;
1675 $list = '';
1676
1677 foreach ( $a as $field => $value ) {
1678 if ( !$first ) {
1679 if ( $mode == LIST_AND ) {
1680 $list .= ' AND ';
1681 } elseif ( $mode == LIST_OR ) {
1682 $list .= ' OR ';
1683 } else {
1684 $list .= ',';
1685 }
1686 } else {
1687 $first = false;
1688 }
1689
1690 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1691 $list .= "($value)";
1692 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1693 $list .= "$value";
1694 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1695 // Remove null from array to be handled separately if found
1696 $includeNull = false;
1697 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1698 $includeNull = true;
1699 unset( $value[$nullKey] );
1700 }
1701 if ( count( $value ) == 0 && !$includeNull ) {
1702 throw new InvalidArgumentException( __METHOD__ . ": empty input for field $field" );
1703 } elseif ( count( $value ) == 0 ) {
1704 // only check if $field is null
1705 $list .= "$field IS NULL";
1706 } else {
1707 // IN clause contains at least one valid element
1708 if ( $includeNull ) {
1709 // Group subconditions to ensure correct precedence
1710 $list .= '(';
1711 }
1712 if ( count( $value ) == 1 ) {
1713 // Special-case single values, as IN isn't terribly efficient
1714 // Don't necessarily assume the single key is 0; we don't
1715 // enforce linear numeric ordering on other arrays here.
1716 $value = array_values( $value )[0];
1717 $list .= $field . " = " . $this->addQuotes( $value );
1718 } else {
1719 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1720 }
1721 // if null present in array, append IS NULL
1722 if ( $includeNull ) {
1723 $list .= " OR $field IS NULL)";
1724 }
1725 }
1726 } elseif ( $value === null ) {
1727 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1728 $list .= "$field IS ";
1729 } elseif ( $mode == LIST_SET ) {
1730 $list .= "$field = ";
1731 }
1732 $list .= 'NULL';
1733 } else {
1734 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1735 $list .= "$field = ";
1736 }
1737 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1738 }
1739 }
1740
1741 return $list;
1742 }
1743
1744 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1745 $conds = [];
1746
1747 foreach ( $data as $base => $sub ) {
1748 if ( count( $sub ) ) {
1749 $conds[] = $this->makeList(
1750 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1751 LIST_AND );
1752 }
1753 }
1754
1755 if ( $conds ) {
1756 return $this->makeList( $conds, LIST_OR );
1757 } else {
1758 // Nothing to search for...
1759 return false;
1760 }
1761 }
1762
1763 /**
1764 * Return aggregated value alias
1765 *
1766 * @param array $valuedata
1767 * @param string $valuename
1768 *
1769 * @return string
1770 */
1771 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1772 return $valuename;
1773 }
1774
1775 public function bitNot( $field ) {
1776 return "(~$field)";
1777 }
1778
1779 public function bitAnd( $fieldLeft, $fieldRight ) {
1780 return "($fieldLeft & $fieldRight)";
1781 }
1782
1783 public function bitOr( $fieldLeft, $fieldRight ) {
1784 return "($fieldLeft | $fieldRight)";
1785 }
1786
1787 public function buildConcat( $stringList ) {
1788 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1789 }
1790
1791 public function buildGroupConcatField(
1792 $delim, $table, $field, $conds = '', $join_conds = []
1793 ) {
1794 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1795
1796 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1797 }
1798
1799 /**
1800 * @param string $field Field or column to cast
1801 * @return string
1802 * @since 1.28
1803 */
1804 public function buildStringCast( $field ) {
1805 return $field;
1806 }
1807
1808 public function selectDB( $db ) {
1809 # Stub. Shouldn't cause serious problems if it's not overridden, but
1810 # if your database engine supports a concept similar to MySQL's
1811 # databases you may as well.
1812 $this->mDBname = $db;
1813
1814 return true;
1815 }
1816
1817 public function getDBname() {
1818 return $this->mDBname;
1819 }
1820
1821 public function getServer() {
1822 return $this->mServer;
1823 }
1824
1825 /**
1826 * Format a table name ready for use in constructing an SQL query
1827 *
1828 * This does two important things: it quotes the table names to clean them up,
1829 * and it adds a table prefix if only given a table name with no quotes.
1830 *
1831 * All functions of this object which require a table name call this function
1832 * themselves. Pass the canonical name to such functions. This is only needed
1833 * when calling query() directly.
1834 *
1835 * @note This function does not sanitize user input. It is not safe to use
1836 * this function to escape user input.
1837 * @param string $name Database table name
1838 * @param string $format One of:
1839 * quoted - Automatically pass the table name through addIdentifierQuotes()
1840 * so that it can be used in a query.
1841 * raw - Do not add identifier quotes to the table name
1842 * @return string Full database name
1843 */
1844 public function tableName( $name, $format = 'quoted' ) {
1845 # Skip the entire process when we have a string quoted on both ends.
1846 # Note that we check the end so that we will still quote any use of
1847 # use of `database`.table. But won't break things if someone wants
1848 # to query a database table with a dot in the name.
1849 if ( $this->isQuotedIdentifier( $name ) ) {
1850 return $name;
1851 }
1852
1853 # Lets test for any bits of text that should never show up in a table
1854 # name. Basically anything like JOIN or ON which are actually part of
1855 # SQL queries, but may end up inside of the table value to combine
1856 # sql. Such as how the API is doing.
1857 # Note that we use a whitespace test rather than a \b test to avoid
1858 # any remote case where a word like on may be inside of a table name
1859 # surrounded by symbols which may be considered word breaks.
1860 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1861 return $name;
1862 }
1863
1864 # Split database and table into proper variables.
1865 # We reverse the explode so that database.table and table both output
1866 # the correct table.
1867 $dbDetails = explode( '.', $name, 3 );
1868 if ( count( $dbDetails ) == 3 ) {
1869 list( $database, $schema, $table ) = $dbDetails;
1870 # We don't want any prefix added in this case
1871 $prefix = '';
1872 } elseif ( count( $dbDetails ) == 2 ) {
1873 list( $database, $table ) = $dbDetails;
1874 # We don't want any prefix added in this case
1875 # In dbs that support it, $database may actually be the schema
1876 # but that doesn't affect any of the functionality here
1877 $prefix = '';
1878 $schema = null;
1879 } else {
1880 list( $table ) = $dbDetails;
1881 if ( isset( $this->tableAliases[$table] ) ) {
1882 $database = $this->tableAliases[$table]['dbname'];
1883 $schema = is_string( $this->tableAliases[$table]['schema'] )
1884 ? $this->tableAliases[$table]['schema']
1885 : $this->mSchema;
1886 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1887 ? $this->tableAliases[$table]['prefix']
1888 : $this->mTablePrefix;
1889 } else {
1890 $database = null;
1891 $schema = $this->mSchema; # Default schema
1892 $prefix = $this->mTablePrefix; # Default prefix
1893 }
1894 }
1895
1896 # Quote $table and apply the prefix if not quoted.
1897 # $tableName might be empty if this is called from Database::replaceVars()
1898 $tableName = "{$prefix}{$table}";
1899 if ( $format == 'quoted'
1900 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1901 ) {
1902 $tableName = $this->addIdentifierQuotes( $tableName );
1903 }
1904
1905 # Quote $schema and merge it with the table name if needed
1906 if ( strlen( $schema ) ) {
1907 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1908 $schema = $this->addIdentifierQuotes( $schema );
1909 }
1910 $tableName = $schema . '.' . $tableName;
1911 }
1912
1913 # Quote $database and merge it with the table name if needed
1914 if ( $database !== null ) {
1915 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1916 $database = $this->addIdentifierQuotes( $database );
1917 }
1918 $tableName = $database . '.' . $tableName;
1919 }
1920
1921 return $tableName;
1922 }
1923
1924 /**
1925 * Fetch a number of table names into an array
1926 * This is handy when you need to construct SQL for joins
1927 *
1928 * Example:
1929 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1930 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1931 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1932 *
1933 * @return array
1934 */
1935 public function tableNames() {
1936 $inArray = func_get_args();
1937 $retVal = [];
1938
1939 foreach ( $inArray as $name ) {
1940 $retVal[$name] = $this->tableName( $name );
1941 }
1942
1943 return $retVal;
1944 }
1945
1946 /**
1947 * Fetch a number of table names into an zero-indexed numerical array
1948 * This is handy when you need to construct SQL for joins
1949 *
1950 * Example:
1951 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1952 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1953 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1954 *
1955 * @return array
1956 */
1957 public function tableNamesN() {
1958 $inArray = func_get_args();
1959 $retVal = [];
1960
1961 foreach ( $inArray as $name ) {
1962 $retVal[] = $this->tableName( $name );
1963 }
1964
1965 return $retVal;
1966 }
1967
1968 /**
1969 * Get an aliased table name
1970 * e.g. tableName AS newTableName
1971 *
1972 * @param string $name Table name, see tableName()
1973 * @param string|bool $alias Alias (optional)
1974 * @return string SQL name for aliased table. Will not alias a table to its own name
1975 */
1976 public function tableNameWithAlias( $name, $alias = false ) {
1977 if ( !$alias || $alias == $name ) {
1978 return $this->tableName( $name );
1979 } else {
1980 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1981 }
1982 }
1983
1984 /**
1985 * Gets an array of aliased table names
1986 *
1987 * @param array $tables [ [alias] => table ]
1988 * @return string[] See tableNameWithAlias()
1989 */
1990 public function tableNamesWithAlias( $tables ) {
1991 $retval = [];
1992 foreach ( $tables as $alias => $table ) {
1993 if ( is_numeric( $alias ) ) {
1994 $alias = $table;
1995 }
1996 $retval[] = $this->tableNameWithAlias( $table, $alias );
1997 }
1998
1999 return $retval;
2000 }
2001
2002 /**
2003 * Get an aliased field name
2004 * e.g. fieldName AS newFieldName
2005 *
2006 * @param string $name Field name
2007 * @param string|bool $alias Alias (optional)
2008 * @return string SQL name for aliased field. Will not alias a field to its own name
2009 */
2010 public function fieldNameWithAlias( $name, $alias = false ) {
2011 if ( !$alias || (string)$alias === (string)$name ) {
2012 return $name;
2013 } else {
2014 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2015 }
2016 }
2017
2018 /**
2019 * Gets an array of aliased field names
2020 *
2021 * @param array $fields [ [alias] => field ]
2022 * @return string[] See fieldNameWithAlias()
2023 */
2024 public function fieldNamesWithAlias( $fields ) {
2025 $retval = [];
2026 foreach ( $fields as $alias => $field ) {
2027 if ( is_numeric( $alias ) ) {
2028 $alias = $field;
2029 }
2030 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2031 }
2032
2033 return $retval;
2034 }
2035
2036 /**
2037 * Get the aliased table name clause for a FROM clause
2038 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2039 *
2040 * @param array $tables ( [alias] => table )
2041 * @param array $use_index Same as for select()
2042 * @param array $ignore_index Same as for select()
2043 * @param array $join_conds Same as for select()
2044 * @return string
2045 */
2046 protected function tableNamesWithIndexClauseOrJOIN(
2047 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2048 ) {
2049 $ret = [];
2050 $retJOIN = [];
2051 $use_index = (array)$use_index;
2052 $ignore_index = (array)$ignore_index;
2053 $join_conds = (array)$join_conds;
2054
2055 foreach ( $tables as $alias => $table ) {
2056 if ( !is_string( $alias ) ) {
2057 // No alias? Set it equal to the table name
2058 $alias = $table;
2059 }
2060 // Is there a JOIN clause for this table?
2061 if ( isset( $join_conds[$alias] ) ) {
2062 list( $joinType, $conds ) = $join_conds[$alias];
2063 $tableClause = $joinType;
2064 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2065 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2066 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2067 if ( $use != '' ) {
2068 $tableClause .= ' ' . $use;
2069 }
2070 }
2071 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2072 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2073 if ( $ignore != '' ) {
2074 $tableClause .= ' ' . $ignore;
2075 }
2076 }
2077 $on = $this->makeList( (array)$conds, LIST_AND );
2078 if ( $on != '' ) {
2079 $tableClause .= ' ON (' . $on . ')';
2080 }
2081
2082 $retJOIN[] = $tableClause;
2083 } elseif ( isset( $use_index[$alias] ) ) {
2084 // Is there an INDEX clause for this table?
2085 $tableClause = $this->tableNameWithAlias( $table, $alias );
2086 $tableClause .= ' ' . $this->useIndexClause(
2087 implode( ',', (array)$use_index[$alias] )
2088 );
2089
2090 $ret[] = $tableClause;
2091 } elseif ( isset( $ignore_index[$alias] ) ) {
2092 // Is there an INDEX clause for this table?
2093 $tableClause = $this->tableNameWithAlias( $table, $alias );
2094 $tableClause .= ' ' . $this->ignoreIndexClause(
2095 implode( ',', (array)$ignore_index[$alias] )
2096 );
2097
2098 $ret[] = $tableClause;
2099 } else {
2100 $tableClause = $this->tableNameWithAlias( $table, $alias );
2101
2102 $ret[] = $tableClause;
2103 }
2104 }
2105
2106 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2107 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2108 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2109
2110 // Compile our final table clause
2111 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2112 }
2113
2114 /**
2115 * Get the name of an index in a given table.
2116 *
2117 * @param string $index
2118 * @return string
2119 */
2120 protected function indexName( $index ) {
2121 // Backwards-compatibility hack
2122 $renamed = [
2123 'ar_usertext_timestamp' => 'usertext_timestamp',
2124 'un_user_id' => 'user_id',
2125 'un_user_ip' => 'user_ip',
2126 ];
2127
2128 if ( isset( $renamed[$index] ) ) {
2129 return $renamed[$index];
2130 } else {
2131 return $index;
2132 }
2133 }
2134
2135 public function addQuotes( $s ) {
2136 if ( $s instanceof Blob ) {
2137 $s = $s->fetch();
2138 }
2139 if ( $s === null ) {
2140 return 'NULL';
2141 } else {
2142 # This will also quote numeric values. This should be harmless,
2143 # and protects against weird problems that occur when they really
2144 # _are_ strings such as article titles and string->number->string
2145 # conversion is not 1:1.
2146 return "'" . $this->strencode( $s ) . "'";
2147 }
2148 }
2149
2150 /**
2151 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2152 * MySQL uses `backticks` while basically everything else uses double quotes.
2153 * Since MySQL is the odd one out here the double quotes are our generic
2154 * and we implement backticks in DatabaseMysql.
2155 *
2156 * @param string $s
2157 * @return string
2158 */
2159 public function addIdentifierQuotes( $s ) {
2160 return '"' . str_replace( '"', '""', $s ) . '"';
2161 }
2162
2163 /**
2164 * Returns if the given identifier looks quoted or not according to
2165 * the database convention for quoting identifiers .
2166 *
2167 * @note Do not use this to determine if untrusted input is safe.
2168 * A malicious user can trick this function.
2169 * @param string $name
2170 * @return bool
2171 */
2172 public function isQuotedIdentifier( $name ) {
2173 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2174 }
2175
2176 /**
2177 * @param string $s
2178 * @return string
2179 */
2180 protected function escapeLikeInternal( $s ) {
2181 return addcslashes( $s, '\%_' );
2182 }
2183
2184 public function buildLike() {
2185 $params = func_get_args();
2186
2187 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2188 $params = $params[0];
2189 }
2190
2191 $s = '';
2192
2193 foreach ( $params as $value ) {
2194 if ( $value instanceof LikeMatch ) {
2195 $s .= $value->toString();
2196 } else {
2197 $s .= $this->escapeLikeInternal( $value );
2198 }
2199 }
2200
2201 return " LIKE {$this->addQuotes( $s )} ";
2202 }
2203
2204 public function anyChar() {
2205 return new LikeMatch( '_' );
2206 }
2207
2208 public function anyString() {
2209 return new LikeMatch( '%' );
2210 }
2211
2212 public function nextSequenceValue( $seqName ) {
2213 return null;
2214 }
2215
2216 /**
2217 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2218 * is only needed because a) MySQL must be as efficient as possible due to
2219 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2220 * which index to pick. Anyway, other databases might have different
2221 * indexes on a given table. So don't bother overriding this unless you're
2222 * MySQL.
2223 * @param string $index
2224 * @return string
2225 */
2226 public function useIndexClause( $index ) {
2227 return '';
2228 }
2229
2230 /**
2231 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2232 * is only needed because a) MySQL must be as efficient as possible due to
2233 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2234 * which index to pick. Anyway, other databases might have different
2235 * indexes on a given table. So don't bother overriding this unless you're
2236 * MySQL.
2237 * @param string $index
2238 * @return string
2239 */
2240 public function ignoreIndexClause( $index ) {
2241 return '';
2242 }
2243
2244 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2245 $quotedTable = $this->tableName( $table );
2246
2247 if ( count( $rows ) == 0 ) {
2248 return;
2249 }
2250
2251 # Single row case
2252 if ( !is_array( reset( $rows ) ) ) {
2253 $rows = [ $rows ];
2254 }
2255
2256 // @FXIME: this is not atomic, but a trx would break affectedRows()
2257 foreach ( $rows as $row ) {
2258 # Delete rows which collide
2259 if ( $uniqueIndexes ) {
2260 $sql = "DELETE FROM $quotedTable WHERE ";
2261 $first = true;
2262 foreach ( $uniqueIndexes as $index ) {
2263 if ( $first ) {
2264 $first = false;
2265 $sql .= '( ';
2266 } else {
2267 $sql .= ' ) OR ( ';
2268 }
2269 if ( is_array( $index ) ) {
2270 $first2 = true;
2271 foreach ( $index as $col ) {
2272 if ( $first2 ) {
2273 $first2 = false;
2274 } else {
2275 $sql .= ' AND ';
2276 }
2277 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2278 }
2279 } else {
2280 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2281 }
2282 }
2283 $sql .= ' )';
2284 $this->query( $sql, $fname );
2285 }
2286
2287 # Now insert the row
2288 $this->insert( $table, $row, $fname );
2289 }
2290 }
2291
2292 /**
2293 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2294 * statement.
2295 *
2296 * @param string $table Table name
2297 * @param array|string $rows Row(s) to insert
2298 * @param string $fname Caller function name
2299 *
2300 * @return ResultWrapper
2301 */
2302 protected function nativeReplace( $table, $rows, $fname ) {
2303 $table = $this->tableName( $table );
2304
2305 # Single row case
2306 if ( !is_array( reset( $rows ) ) ) {
2307 $rows = [ $rows ];
2308 }
2309
2310 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2311 $first = true;
2312
2313 foreach ( $rows as $row ) {
2314 if ( $first ) {
2315 $first = false;
2316 } else {
2317 $sql .= ',';
2318 }
2319
2320 $sql .= '(' . $this->makeList( $row ) . ')';
2321 }
2322
2323 return $this->query( $sql, $fname );
2324 }
2325
2326 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2327 $fname = __METHOD__
2328 ) {
2329 if ( !count( $rows ) ) {
2330 return true; // nothing to do
2331 }
2332
2333 if ( !is_array( reset( $rows ) ) ) {
2334 $rows = [ $rows ];
2335 }
2336
2337 if ( count( $uniqueIndexes ) ) {
2338 $clauses = []; // list WHERE clauses that each identify a single row
2339 foreach ( $rows as $row ) {
2340 foreach ( $uniqueIndexes as $index ) {
2341 $index = is_array( $index ) ? $index : [ $index ]; // columns
2342 $rowKey = []; // unique key to this row
2343 foreach ( $index as $column ) {
2344 $rowKey[$column] = $row[$column];
2345 }
2346 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2347 }
2348 }
2349 $where = [ $this->makeList( $clauses, LIST_OR ) ];
2350 } else {
2351 $where = false;
2352 }
2353
2354 $useTrx = !$this->mTrxLevel;
2355 if ( $useTrx ) {
2356 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2357 }
2358 try {
2359 # Update any existing conflicting row(s)
2360 if ( $where !== false ) {
2361 $ok = $this->update( $table, $set, $where, $fname );
2362 } else {
2363 $ok = true;
2364 }
2365 # Now insert any non-conflicting row(s)
2366 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2367 } catch ( Exception $e ) {
2368 if ( $useTrx ) {
2369 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2370 }
2371 throw $e;
2372 }
2373 if ( $useTrx ) {
2374 $this->commit( $fname, self::FLUSHING_INTERNAL );
2375 }
2376
2377 return $ok;
2378 }
2379
2380 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2381 $fname = __METHOD__
2382 ) {
2383 if ( !$conds ) {
2384 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2385 }
2386
2387 $delTable = $this->tableName( $delTable );
2388 $joinTable = $this->tableName( $joinTable );
2389 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2390 if ( $conds != '*' ) {
2391 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2392 }
2393 $sql .= ')';
2394
2395 $this->query( $sql, $fname );
2396 }
2397
2398 /**
2399 * Returns the size of a text field, or -1 for "unlimited"
2400 *
2401 * @param string $table
2402 * @param string $field
2403 * @return int
2404 */
2405 public function textFieldSize( $table, $field ) {
2406 $table = $this->tableName( $table );
2407 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2408 $res = $this->query( $sql, __METHOD__ );
2409 $row = $this->fetchObject( $res );
2410
2411 $m = [];
2412
2413 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2414 $size = $m[1];
2415 } else {
2416 $size = -1;
2417 }
2418
2419 return $size;
2420 }
2421
2422 /**
2423 * A string to insert into queries to show that they're low-priority, like
2424 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2425 * string and nothing bad should happen.
2426 *
2427 * @return string Returns the text of the low priority option if it is
2428 * supported, or a blank string otherwise
2429 */
2430 public function lowPriorityOption() {
2431 return '';
2432 }
2433
2434 public function delete( $table, $conds, $fname = __METHOD__ ) {
2435 if ( !$conds ) {
2436 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2437 }
2438
2439 $table = $this->tableName( $table );
2440 $sql = "DELETE FROM $table";
2441
2442 if ( $conds != '*' ) {
2443 if ( is_array( $conds ) ) {
2444 $conds = $this->makeList( $conds, LIST_AND );
2445 }
2446 $sql .= ' WHERE ' . $conds;
2447 }
2448
2449 return $this->query( $sql, $fname );
2450 }
2451
2452 public function insertSelect(
2453 $destTable, $srcTable, $varMap, $conds,
2454 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2455 ) {
2456 if ( $this->cliMode ) {
2457 // For massive migrations with downtime, we don't want to select everything
2458 // into memory and OOM, so do all this native on the server side if possible.
2459 return $this->nativeInsertSelect(
2460 $destTable,
2461 $srcTable,
2462 $varMap,
2463 $conds,
2464 $fname,
2465 $insertOptions,
2466 $selectOptions
2467 );
2468 }
2469
2470 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2471 // on only the master (without needing row-based-replication). It also makes it easy to
2472 // know how big the INSERT is going to be.
2473 $fields = [];
2474 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2475 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2476 }
2477 $selectOptions[] = 'FOR UPDATE';
2478 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2479 if ( !$res ) {
2480 return false;
2481 }
2482
2483 $rows = [];
2484 foreach ( $res as $row ) {
2485 $rows[] = (array)$row;
2486 }
2487
2488 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2489 }
2490
2491 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2492 $fname = __METHOD__,
2493 $insertOptions = [], $selectOptions = []
2494 ) {
2495 $destTable = $this->tableName( $destTable );
2496
2497 if ( !is_array( $insertOptions ) ) {
2498 $insertOptions = [ $insertOptions ];
2499 }
2500
2501 $insertOptions = $this->makeInsertOptions( $insertOptions );
2502
2503 if ( !is_array( $selectOptions ) ) {
2504 $selectOptions = [ $selectOptions ];
2505 }
2506
2507 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2508 $selectOptions );
2509
2510 if ( is_array( $srcTable ) ) {
2511 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2512 } else {
2513 $srcTable = $this->tableName( $srcTable );
2514 }
2515
2516 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2517 " SELECT $startOpts " . implode( ',', $varMap ) .
2518 " FROM $srcTable $useIndex $ignoreIndex ";
2519
2520 if ( $conds != '*' ) {
2521 if ( is_array( $conds ) ) {
2522 $conds = $this->makeList( $conds, LIST_AND );
2523 }
2524 $sql .= " WHERE $conds";
2525 }
2526
2527 $sql .= " $tailOpts";
2528
2529 return $this->query( $sql, $fname );
2530 }
2531
2532 /**
2533 * Construct a LIMIT query with optional offset. This is used for query
2534 * pages. The SQL should be adjusted so that only the first $limit rows
2535 * are returned. If $offset is provided as well, then the first $offset
2536 * rows should be discarded, and the next $limit rows should be returned.
2537 * If the result of the query is not ordered, then the rows to be returned
2538 * are theoretically arbitrary.
2539 *
2540 * $sql is expected to be a SELECT, if that makes a difference.
2541 *
2542 * The version provided by default works in MySQL and SQLite. It will very
2543 * likely need to be overridden for most other DBMSes.
2544 *
2545 * @param string $sql SQL query we will append the limit too
2546 * @param int $limit The SQL limit
2547 * @param int|bool $offset The SQL offset (default false)
2548 * @throws DBUnexpectedError
2549 * @return string
2550 */
2551 public function limitResult( $sql, $limit, $offset = false ) {
2552 if ( !is_numeric( $limit ) ) {
2553 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2554 }
2555
2556 return "$sql LIMIT "
2557 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2558 . "{$limit} ";
2559 }
2560
2561 public function unionSupportsOrderAndLimit() {
2562 return true; // True for almost every DB supported
2563 }
2564
2565 public function unionQueries( $sqls, $all ) {
2566 $glue = $all ? ') UNION ALL (' : ') UNION (';
2567
2568 return '(' . implode( $glue, $sqls ) . ')';
2569 }
2570
2571 public function conditional( $cond, $trueVal, $falseVal ) {
2572 if ( is_array( $cond ) ) {
2573 $cond = $this->makeList( $cond, LIST_AND );
2574 }
2575
2576 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2577 }
2578
2579 public function strreplace( $orig, $old, $new ) {
2580 return "REPLACE({$orig}, {$old}, {$new})";
2581 }
2582
2583 public function getServerUptime() {
2584 return 0;
2585 }
2586
2587 public function wasDeadlock() {
2588 return false;
2589 }
2590
2591 public function wasLockTimeout() {
2592 return false;
2593 }
2594
2595 public function wasErrorReissuable() {
2596 return false;
2597 }
2598
2599 public function wasReadOnlyError() {
2600 return false;
2601 }
2602
2603 /**
2604 * Determines if the given query error was a connection drop
2605 * STUB
2606 *
2607 * @param integer|string $errno
2608 * @return bool
2609 */
2610 public function wasConnectionError( $errno ) {
2611 return false;
2612 }
2613
2614 /**
2615 * Perform a deadlock-prone transaction.
2616 *
2617 * This function invokes a callback function to perform a set of write
2618 * queries. If a deadlock occurs during the processing, the transaction
2619 * will be rolled back and the callback function will be called again.
2620 *
2621 * Avoid using this method outside of Job or Maintenance classes.
2622 *
2623 * Usage:
2624 * $dbw->deadlockLoop( callback, ... );
2625 *
2626 * Extra arguments are passed through to the specified callback function.
2627 * This method requires that no transactions are already active to avoid
2628 * causing premature commits or exceptions.
2629 *
2630 * Returns whatever the callback function returned on its successful,
2631 * iteration, or false on error, for example if the retry limit was
2632 * reached.
2633 *
2634 * @return mixed
2635 * @throws DBUnexpectedError
2636 * @throws Exception
2637 */
2638 public function deadlockLoop() {
2639 $args = func_get_args();
2640 $function = array_shift( $args );
2641 $tries = self::DEADLOCK_TRIES;
2642
2643 $this->begin( __METHOD__ );
2644
2645 $retVal = null;
2646 /** @var Exception $e */
2647 $e = null;
2648 do {
2649 try {
2650 $retVal = call_user_func_array( $function, $args );
2651 break;
2652 } catch ( DBQueryError $e ) {
2653 if ( $this->wasDeadlock() ) {
2654 // Retry after a randomized delay
2655 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2656 } else {
2657 // Throw the error back up
2658 throw $e;
2659 }
2660 }
2661 } while ( --$tries > 0 );
2662
2663 if ( $tries <= 0 ) {
2664 // Too many deadlocks; give up
2665 $this->rollback( __METHOD__ );
2666 throw $e;
2667 } else {
2668 $this->commit( __METHOD__ );
2669
2670 return $retVal;
2671 }
2672 }
2673
2674 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2675 # Real waits are implemented in the subclass.
2676 return 0;
2677 }
2678
2679 public function getSlavePos() {
2680 # Stub
2681 return false;
2682 }
2683
2684 public function getMasterPos() {
2685 # Stub
2686 return false;
2687 }
2688
2689 public function serverIsReadOnly() {
2690 return false;
2691 }
2692
2693 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2694 if ( !$this->mTrxLevel ) {
2695 throw new DBUnexpectedError( $this, "No transaction is active." );
2696 }
2697 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2698 }
2699
2700 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2701 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2702 if ( !$this->mTrxLevel ) {
2703 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2704 }
2705 }
2706
2707 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2708 if ( $this->mTrxLevel ) {
2709 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2710 } else {
2711 // If no transaction is active, then make one for this callback
2712 $this->startAtomic( __METHOD__ );
2713 try {
2714 call_user_func( $callback );
2715 $this->endAtomic( __METHOD__ );
2716 } catch ( Exception $e ) {
2717 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2718 throw $e;
2719 }
2720 }
2721 }
2722
2723 final public function setTransactionListener( $name, callable $callback = null ) {
2724 if ( $callback ) {
2725 $this->mTrxRecurringCallbacks[$name] = $callback;
2726 } else {
2727 unset( $this->mTrxRecurringCallbacks[$name] );
2728 }
2729 }
2730
2731 /**
2732 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2733 *
2734 * This method should not be used outside of Database/LoadBalancer
2735 *
2736 * @param bool $suppress
2737 * @since 1.28
2738 */
2739 final public function setTrxEndCallbackSuppression( $suppress ) {
2740 $this->mTrxEndCallbacksSuppressed = $suppress;
2741 }
2742
2743 /**
2744 * Actually run and consume any "on transaction idle/resolution" callbacks.
2745 *
2746 * This method should not be used outside of Database/LoadBalancer
2747 *
2748 * @param integer $trigger IDatabase::TRIGGER_* constant
2749 * @since 1.20
2750 * @throws Exception
2751 */
2752 public function runOnTransactionIdleCallbacks( $trigger ) {
2753 if ( $this->mTrxEndCallbacksSuppressed ) {
2754 return;
2755 }
2756
2757 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
2758 /** @var Exception $e */
2759 $e = null; // first exception
2760 do { // callbacks may add callbacks :)
2761 $callbacks = array_merge(
2762 $this->mTrxIdleCallbacks,
2763 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2764 );
2765 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2766 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2767 foreach ( $callbacks as $callback ) {
2768 try {
2769 list( $phpCallback ) = $callback;
2770 $this->clearFlag( DBO_TRX ); // make each query its own transaction
2771 call_user_func_array( $phpCallback, [ $trigger ] );
2772 if ( $autoTrx ) {
2773 $this->setFlag( DBO_TRX ); // restore automatic begin()
2774 } else {
2775 $this->clearFlag( DBO_TRX ); // restore auto-commit
2776 }
2777 } catch ( Exception $ex ) {
2778 call_user_func( $this->errorLogger, $ex );
2779 $e = $e ?: $ex;
2780 // Some callbacks may use startAtomic/endAtomic, so make sure
2781 // their transactions are ended so other callbacks don't fail
2782 if ( $this->trxLevel() ) {
2783 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2784 }
2785 }
2786 }
2787 } while ( count( $this->mTrxIdleCallbacks ) );
2788
2789 if ( $e instanceof Exception ) {
2790 throw $e; // re-throw any first exception
2791 }
2792 }
2793
2794 /**
2795 * Actually run and consume any "on transaction pre-commit" callbacks.
2796 *
2797 * This method should not be used outside of Database/LoadBalancer
2798 *
2799 * @since 1.22
2800 * @throws Exception
2801 */
2802 public function runOnTransactionPreCommitCallbacks() {
2803 $e = null; // first exception
2804 do { // callbacks may add callbacks :)
2805 $callbacks = $this->mTrxPreCommitCallbacks;
2806 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2807 foreach ( $callbacks as $callback ) {
2808 try {
2809 list( $phpCallback ) = $callback;
2810 call_user_func( $phpCallback );
2811 } catch ( Exception $ex ) {
2812 call_user_func( $this->errorLogger, $ex );
2813 $e = $e ?: $ex;
2814 }
2815 }
2816 } while ( count( $this->mTrxPreCommitCallbacks ) );
2817
2818 if ( $e instanceof Exception ) {
2819 throw $e; // re-throw any first exception
2820 }
2821 }
2822
2823 /**
2824 * Actually run any "transaction listener" callbacks.
2825 *
2826 * This method should not be used outside of Database/LoadBalancer
2827 *
2828 * @param integer $trigger IDatabase::TRIGGER_* constant
2829 * @throws Exception
2830 * @since 1.20
2831 */
2832 public function runTransactionListenerCallbacks( $trigger ) {
2833 if ( $this->mTrxEndCallbacksSuppressed ) {
2834 return;
2835 }
2836
2837 /** @var Exception $e */
2838 $e = null; // first exception
2839
2840 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2841 try {
2842 $phpCallback( $trigger, $this );
2843 } catch ( Exception $ex ) {
2844 call_user_func( $this->errorLogger, $ex );
2845 $e = $e ?: $ex;
2846 }
2847 }
2848
2849 if ( $e instanceof Exception ) {
2850 throw $e; // re-throw any first exception
2851 }
2852 }
2853
2854 final public function startAtomic( $fname = __METHOD__ ) {
2855 if ( !$this->mTrxLevel ) {
2856 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2857 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2858 // in all changes being in one transaction to keep requests transactional.
2859 if ( !$this->getFlag( DBO_TRX ) ) {
2860 $this->mTrxAutomaticAtomic = true;
2861 }
2862 }
2863
2864 $this->mTrxAtomicLevels[] = $fname;
2865 }
2866
2867 final public function endAtomic( $fname = __METHOD__ ) {
2868 if ( !$this->mTrxLevel ) {
2869 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2870 }
2871 if ( !$this->mTrxAtomicLevels ||
2872 array_pop( $this->mTrxAtomicLevels ) !== $fname
2873 ) {
2874 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2875 }
2876
2877 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2878 $this->commit( $fname, self::FLUSHING_INTERNAL );
2879 }
2880 }
2881
2882 final public function doAtomicSection( $fname, callable $callback ) {
2883 $this->startAtomic( $fname );
2884 try {
2885 $res = call_user_func_array( $callback, [ $this, $fname ] );
2886 } catch ( Exception $e ) {
2887 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2888 throw $e;
2889 }
2890 $this->endAtomic( $fname );
2891
2892 return $res;
2893 }
2894
2895 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2896 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2897 if ( $this->mTrxLevel ) {
2898 if ( $this->mTrxAtomicLevels ) {
2899 $levels = implode( ', ', $this->mTrxAtomicLevels );
2900 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2901 throw new DBUnexpectedError( $this, $msg );
2902 } elseif ( !$this->mTrxAutomatic ) {
2903 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2904 throw new DBUnexpectedError( $this, $msg );
2905 } else {
2906 // @TODO: make this an exception at some point
2907 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2908 $this->queryLogger->error( $msg );
2909 return; // join the main transaction set
2910 }
2911 } elseif ( $this->getFlag( DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2912 // @TODO: make this an exception at some point
2913 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2914 $this->queryLogger->error( $msg );
2915 return; // let any writes be in the main transaction
2916 }
2917
2918 // Avoid fatals if close() was called
2919 $this->assertOpen();
2920
2921 $this->doBegin( $fname );
2922 $this->mTrxTimestamp = microtime( true );
2923 $this->mTrxFname = $fname;
2924 $this->mTrxDoneWrites = false;
2925 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2926 $this->mTrxAutomaticAtomic = false;
2927 $this->mTrxAtomicLevels = [];
2928 $this->mTrxShortId = wfRandomString( 12 );
2929 $this->mTrxWriteDuration = 0.0;
2930 $this->mTrxWriteQueryCount = 0;
2931 $this->mTrxWriteAdjDuration = 0.0;
2932 $this->mTrxWriteAdjQueryCount = 0;
2933 $this->mTrxWriteCallers = [];
2934 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2935 // Get an estimate of the replica DB lag before then, treating estimate staleness
2936 // as lag itself just to be safe
2937 $status = $this->getApproximateLagStatus();
2938 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2939 }
2940
2941 /**
2942 * Issues the BEGIN command to the database server.
2943 *
2944 * @see DatabaseBase::begin()
2945 * @param string $fname
2946 */
2947 protected function doBegin( $fname ) {
2948 $this->query( 'BEGIN', $fname );
2949 $this->mTrxLevel = 1;
2950 }
2951
2952 final public function commit( $fname = __METHOD__, $flush = '' ) {
2953 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2954 // There are still atomic sections open. This cannot be ignored
2955 $levels = implode( ', ', $this->mTrxAtomicLevels );
2956 throw new DBUnexpectedError(
2957 $this,
2958 "$fname: Got COMMIT while atomic sections $levels are still open."
2959 );
2960 }
2961
2962 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2963 if ( !$this->mTrxLevel ) {
2964 return; // nothing to do
2965 } elseif ( !$this->mTrxAutomatic ) {
2966 throw new DBUnexpectedError(
2967 $this,
2968 "$fname: Flushing an explicit transaction, getting out of sync."
2969 );
2970 }
2971 } else {
2972 if ( !$this->mTrxLevel ) {
2973 $this->queryLogger->error( "$fname: No transaction to commit, something got out of sync." );
2974 return; // nothing to do
2975 } elseif ( $this->mTrxAutomatic ) {
2976 // @TODO: make this an exception at some point
2977 $msg = "$fname: Explicit commit of implicit transaction.";
2978 $this->queryLogger->error( $msg );
2979 return; // wait for the main transaction set commit round
2980 }
2981 }
2982
2983 // Avoid fatals if close() was called
2984 $this->assertOpen();
2985
2986 $this->runOnTransactionPreCommitCallbacks();
2987 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2988 $this->doCommit( $fname );
2989 if ( $this->mTrxDoneWrites ) {
2990 $this->mDoneWrites = microtime( true );
2991 $this->trxProfiler->transactionWritingOut(
2992 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2993 }
2994
2995 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2996 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2997 }
2998
2999 /**
3000 * Issues the COMMIT command to the database server.
3001 *
3002 * @see DatabaseBase::commit()
3003 * @param string $fname
3004 */
3005 protected function doCommit( $fname ) {
3006 if ( $this->mTrxLevel ) {
3007 $this->query( 'COMMIT', $fname );
3008 $this->mTrxLevel = 0;
3009 }
3010 }
3011
3012 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3013 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3014 if ( !$this->mTrxLevel ) {
3015 return; // nothing to do
3016 }
3017 } else {
3018 if ( !$this->mTrxLevel ) {
3019 $this->queryLogger->error(
3020 "$fname: No transaction to rollback, something got out of sync." );
3021 return; // nothing to do
3022 } elseif ( $this->getFlag( DBO_TRX ) ) {
3023 throw new DBUnexpectedError(
3024 $this,
3025 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3026 );
3027 }
3028 }
3029
3030 // Avoid fatals if close() was called
3031 $this->assertOpen();
3032
3033 $this->doRollback( $fname );
3034 $this->mTrxAtomicLevels = [];
3035 if ( $this->mTrxDoneWrites ) {
3036 $this->trxProfiler->transactionWritingOut(
3037 $this->mServer, $this->mDBname, $this->mTrxShortId );
3038 }
3039
3040 $this->mTrxIdleCallbacks = []; // clear
3041 $this->mTrxPreCommitCallbacks = []; // clear
3042 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3043 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3044 }
3045
3046 /**
3047 * Issues the ROLLBACK command to the database server.
3048 *
3049 * @see DatabaseBase::rollback()
3050 * @param string $fname
3051 */
3052 protected function doRollback( $fname ) {
3053 if ( $this->mTrxLevel ) {
3054 # Disconnects cause rollback anyway, so ignore those errors
3055 $ignoreErrors = true;
3056 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3057 $this->mTrxLevel = 0;
3058 }
3059 }
3060
3061 public function flushSnapshot( $fname = __METHOD__ ) {
3062 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3063 // This only flushes transactions to clear snapshots, not to write data
3064 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3065 throw new DBUnexpectedError(
3066 $this,
3067 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3068 );
3069 }
3070
3071 $this->commit( $fname, self::FLUSHING_INTERNAL );
3072 }
3073
3074 public function explicitTrxActive() {
3075 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
3076 }
3077
3078 /**
3079 * Creates a new table with structure copied from existing table
3080 * Note that unlike most database abstraction functions, this function does not
3081 * automatically append database prefix, because it works at a lower
3082 * abstraction level.
3083 * The table names passed to this function shall not be quoted (this
3084 * function calls addIdentifierQuotes when needed).
3085 *
3086 * @param string $oldName Name of table whose structure should be copied
3087 * @param string $newName Name of table to be created
3088 * @param bool $temporary Whether the new table should be temporary
3089 * @param string $fname Calling function name
3090 * @throws RuntimeException
3091 * @return bool True if operation was successful
3092 */
3093 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3094 $fname = __METHOD__
3095 ) {
3096 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3097 }
3098
3099 function listTables( $prefix = null, $fname = __METHOD__ ) {
3100 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3101 }
3102
3103 /**
3104 * Reset the views process cache set by listViews()
3105 * @since 1.22
3106 */
3107 final public function clearViewsCache() {
3108 $this->allViews = null;
3109 }
3110
3111 /**
3112 * Lists all the VIEWs in the database
3113 *
3114 * For caching purposes the list of all views should be stored in
3115 * $this->allViews. The process cache can be cleared with clearViewsCache()
3116 *
3117 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3118 * @param string $fname Name of calling function
3119 * @throws RuntimeException
3120 * @return array
3121 * @since 1.22
3122 */
3123 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3124 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3125 }
3126
3127 /**
3128 * Differentiates between a TABLE and a VIEW
3129 *
3130 * @param string $name Name of the database-structure to test.
3131 * @throws RuntimeException
3132 * @return bool
3133 * @since 1.22
3134 */
3135 public function isView( $name ) {
3136 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3137 }
3138
3139 public function timestamp( $ts = 0 ) {
3140 return wfTimestamp( TS_MW, $ts );
3141 }
3142
3143 public function timestampOrNull( $ts = null ) {
3144 if ( is_null( $ts ) ) {
3145 return null;
3146 } else {
3147 return $this->timestamp( $ts );
3148 }
3149 }
3150
3151 /**
3152 * Take the result from a query, and wrap it in a ResultWrapper if
3153 * necessary. Boolean values are passed through as is, to indicate success
3154 * of write queries or failure.
3155 *
3156 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3157 * resource, and it was necessary to call this function to convert it to
3158 * a wrapper. Nowadays, raw database objects are never exposed to external
3159 * callers, so this is unnecessary in external code.
3160 *
3161 * @param bool|ResultWrapper|resource|object $result
3162 * @return bool|ResultWrapper
3163 */
3164 protected function resultObject( $result ) {
3165 if ( !$result ) {
3166 return false;
3167 } elseif ( $result instanceof ResultWrapper ) {
3168 return $result;
3169 } elseif ( $result === true ) {
3170 // Successful write query
3171 return $result;
3172 } else {
3173 return new ResultWrapper( $this, $result );
3174 }
3175 }
3176
3177 public function ping( &$rtt = null ) {
3178 // Avoid hitting the server if it was hit recently
3179 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3180 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
3181 $rtt = $this->mRTTEstimate;
3182 return true; // don't care about $rtt
3183 }
3184 }
3185
3186 // This will reconnect if possible or return false if not
3187 $this->clearFlag( DBO_TRX, self::REMEMBER_PRIOR );
3188 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3189 $this->restoreFlags( self::RESTORE_PRIOR );
3190
3191 if ( $ok ) {
3192 $rtt = $this->mRTTEstimate;
3193 }
3194
3195 return $ok;
3196 }
3197
3198 /**
3199 * @return bool
3200 */
3201 protected function reconnect() {
3202 $this->closeConnection();
3203 $this->mOpened = false;
3204 $this->mConn = false;
3205 try {
3206 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3207 $this->lastPing = microtime( true );
3208 $ok = true;
3209 } catch ( DBConnectionError $e ) {
3210 $ok = false;
3211 }
3212
3213 return $ok;
3214 }
3215
3216 public function getSessionLagStatus() {
3217 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3218 }
3219
3220 /**
3221 * Get the replica DB lag when the current transaction started
3222 *
3223 * This is useful when transactions might use snapshot isolation
3224 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3225 * is this lag plus transaction duration. If they don't, it is still
3226 * safe to be pessimistic. This returns null if there is no transaction.
3227 *
3228 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3229 * @since 1.27
3230 */
3231 public function getTransactionLagStatus() {
3232 return $this->mTrxLevel
3233 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3234 : null;
3235 }
3236
3237 /**
3238 * Get a replica DB lag estimate for this server
3239 *
3240 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3241 * @since 1.27
3242 */
3243 public function getApproximateLagStatus() {
3244 return [
3245 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3246 'since' => microtime( true )
3247 ];
3248 }
3249
3250 /**
3251 * Merge the result of getSessionLagStatus() for several DBs
3252 * using the most pessimistic values to estimate the lag of
3253 * any data derived from them in combination
3254 *
3255 * This is information is useful for caching modules
3256 *
3257 * @see WANObjectCache::set()
3258 * @see WANObjectCache::getWithSetCallback()
3259 *
3260 * @param IDatabase $db1
3261 * @param IDatabase ...
3262 * @return array Map of values:
3263 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3264 * - since: oldest UNIX timestamp of any of the DB lag estimates
3265 * - pending: whether any of the DBs have uncommitted changes
3266 * @since 1.27
3267 */
3268 public static function getCacheSetOptions( IDatabase $db1 ) {
3269 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3270 foreach ( func_get_args() as $db ) {
3271 /** @var IDatabase $db */
3272 $status = $db->getSessionLagStatus();
3273 if ( $status['lag'] === false ) {
3274 $res['lag'] = false;
3275 } elseif ( $res['lag'] !== false ) {
3276 $res['lag'] = max( $res['lag'], $status['lag'] );
3277 }
3278 $res['since'] = min( $res['since'], $status['since'] );
3279 $res['pending'] = $res['pending'] ?: $db->writesPending();
3280 }
3281
3282 return $res;
3283 }
3284
3285 public function getLag() {
3286 return 0;
3287 }
3288
3289 function maxListLen() {
3290 return 0;
3291 }
3292
3293 public function encodeBlob( $b ) {
3294 return $b;
3295 }
3296
3297 public function decodeBlob( $b ) {
3298 if ( $b instanceof Blob ) {
3299 $b = $b->fetch();
3300 }
3301 return $b;
3302 }
3303
3304 public function setSessionOptions( array $options ) {
3305 }
3306
3307 /**
3308 * Read and execute SQL commands from a file.
3309 *
3310 * Returns true on success, error string or exception on failure (depending
3311 * on object's error ignore settings).
3312 *
3313 * @param string $filename File name to open
3314 * @param bool|callable $lineCallback Optional function called before reading each line
3315 * @param bool|callable $resultCallback Optional function called for each MySQL result
3316 * @param bool|string $fname Calling function name or false if name should be
3317 * generated dynamically using $filename
3318 * @param bool|callable $inputCallback Optional function called for each
3319 * complete line sent
3320 * @return bool|string
3321 * @throws Exception
3322 */
3323 public function sourceFile(
3324 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3325 ) {
3326 MediaWiki\suppressWarnings();
3327 $fp = fopen( $filename, 'r' );
3328 MediaWiki\restoreWarnings();
3329
3330 if ( false === $fp ) {
3331 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3332 }
3333
3334 if ( !$fname ) {
3335 $fname = __METHOD__ . "( $filename )";
3336 }
3337
3338 try {
3339 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3340 } catch ( Exception $e ) {
3341 fclose( $fp );
3342 throw $e;
3343 }
3344
3345 fclose( $fp );
3346
3347 return $error;
3348 }
3349
3350 public function setSchemaVars( $vars ) {
3351 $this->mSchemaVars = $vars;
3352 }
3353
3354 /**
3355 * Read and execute commands from an open file handle.
3356 *
3357 * Returns true on success, error string or exception on failure (depending
3358 * on object's error ignore settings).
3359 *
3360 * @param resource $fp File handle
3361 * @param bool|callable $lineCallback Optional function called before reading each query
3362 * @param bool|callable $resultCallback Optional function called for each MySQL result
3363 * @param string $fname Calling function name
3364 * @param bool|callable $inputCallback Optional function called for each complete query sent
3365 * @return bool|string
3366 */
3367 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3368 $fname = __METHOD__, $inputCallback = false
3369 ) {
3370 $cmd = '';
3371
3372 while ( !feof( $fp ) ) {
3373 if ( $lineCallback ) {
3374 call_user_func( $lineCallback );
3375 }
3376
3377 $line = trim( fgets( $fp ) );
3378
3379 if ( $line == '' ) {
3380 continue;
3381 }
3382
3383 if ( '-' == $line[0] && '-' == $line[1] ) {
3384 continue;
3385 }
3386
3387 if ( $cmd != '' ) {
3388 $cmd .= ' ';
3389 }
3390
3391 $done = $this->streamStatementEnd( $cmd, $line );
3392
3393 $cmd .= "$line\n";
3394
3395 if ( $done || feof( $fp ) ) {
3396 $cmd = $this->replaceVars( $cmd );
3397
3398 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3399 $res = $this->query( $cmd, $fname );
3400
3401 if ( $resultCallback ) {
3402 call_user_func( $resultCallback, $res, $this );
3403 }
3404
3405 if ( false === $res ) {
3406 $err = $this->lastError();
3407
3408 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3409 }
3410 }
3411 $cmd = '';
3412 }
3413 }
3414
3415 return true;
3416 }
3417
3418 /**
3419 * Called by sourceStream() to check if we've reached a statement end
3420 *
3421 * @param string $sql SQL assembled so far
3422 * @param string $newLine New line about to be added to $sql
3423 * @return bool Whether $newLine contains end of the statement
3424 */
3425 public function streamStatementEnd( &$sql, &$newLine ) {
3426 if ( $this->delimiter ) {
3427 $prev = $newLine;
3428 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3429 if ( $newLine != $prev ) {
3430 return true;
3431 }
3432 }
3433
3434 return false;
3435 }
3436
3437 /**
3438 * Database independent variable replacement. Replaces a set of variables
3439 * in an SQL statement with their contents as given by $this->getSchemaVars().
3440 *
3441 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3442 *
3443 * - '{$var}' should be used for text and is passed through the database's
3444 * addQuotes method.
3445 * - `{$var}` should be used for identifiers (e.g. table and database names).
3446 * It is passed through the database's addIdentifierQuotes method which
3447 * can be overridden if the database uses something other than backticks.
3448 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3449 * database's tableName method.
3450 * - / *i* / passes the name that follows through the database's indexName method.
3451 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3452 * its use should be avoided. In 1.24 and older, string encoding was applied.
3453 *
3454 * @param string $ins SQL statement to replace variables in
3455 * @return string The new SQL statement with variables replaced
3456 */
3457 protected function replaceVars( $ins ) {
3458 $vars = $this->getSchemaVars();
3459 return preg_replace_callback(
3460 '!
3461 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3462 \'\{\$ (\w+) }\' | # 3. addQuotes
3463 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3464 /\*\$ (\w+) \*/ # 5. leave unencoded
3465 !x',
3466 function ( $m ) use ( $vars ) {
3467 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3468 // check for both nonexistent keys *and* the empty string.
3469 if ( isset( $m[1] ) && $m[1] !== '' ) {
3470 if ( $m[1] === 'i' ) {
3471 return $this->indexName( $m[2] );
3472 } else {
3473 return $this->tableName( $m[2] );
3474 }
3475 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3476 return $this->addQuotes( $vars[$m[3]] );
3477 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3478 return $this->addIdentifierQuotes( $vars[$m[4]] );
3479 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3480 return $vars[$m[5]];
3481 } else {
3482 return $m[0];
3483 }
3484 },
3485 $ins
3486 );
3487 }
3488
3489 /**
3490 * Get schema variables. If none have been set via setSchemaVars(), then
3491 * use some defaults from the current object.
3492 *
3493 * @return array
3494 */
3495 protected function getSchemaVars() {
3496 if ( $this->mSchemaVars ) {
3497 return $this->mSchemaVars;
3498 } else {
3499 return $this->getDefaultSchemaVars();
3500 }
3501 }
3502
3503 /**
3504 * Get schema variables to use if none have been set via setSchemaVars().
3505 *
3506 * Override this in derived classes to provide variables for tables.sql
3507 * and SQL patch files.
3508 *
3509 * @return array
3510 */
3511 protected function getDefaultSchemaVars() {
3512 return [];
3513 }
3514
3515 public function lockIsFree( $lockName, $method ) {
3516 return true;
3517 }
3518
3519 public function lock( $lockName, $method, $timeout = 5 ) {
3520 $this->mNamedLocksHeld[$lockName] = 1;
3521
3522 return true;
3523 }
3524
3525 public function unlock( $lockName, $method ) {
3526 unset( $this->mNamedLocksHeld[$lockName] );
3527
3528 return true;
3529 }
3530
3531 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3532 if ( $this->writesOrCallbacksPending() ) {
3533 // This only flushes transactions to clear snapshots, not to write data
3534 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3535 throw new DBUnexpectedError(
3536 $this,
3537 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3538 );
3539 }
3540
3541 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3542 return null;
3543 }
3544
3545 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3546 if ( $this->trxLevel() ) {
3547 // There is a good chance an exception was thrown, causing any early return
3548 // from the caller. Let any error handler get a chance to issue rollback().
3549 // If there isn't one, let the error bubble up and trigger server-side rollback.
3550 $this->onTransactionResolution(
3551 function () use ( $lockKey, $fname ) {
3552 $this->unlock( $lockKey, $fname );
3553 },
3554 $fname
3555 );
3556 } else {
3557 $this->unlock( $lockKey, $fname );
3558 }
3559 } );
3560
3561 $this->commit( $fname, self::FLUSHING_INTERNAL );
3562
3563 return $unlocker;
3564 }
3565
3566 public function namedLocksEnqueue() {
3567 return false;
3568 }
3569
3570 /**
3571 * Lock specific tables
3572 *
3573 * @param array $read Array of tables to lock for read access
3574 * @param array $write Array of tables to lock for write access
3575 * @param string $method Name of caller
3576 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3577 * @return bool
3578 */
3579 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3580 return true;
3581 }
3582
3583 /**
3584 * Unlock specific tables
3585 *
3586 * @param string $method The caller
3587 * @return bool
3588 */
3589 public function unlockTables( $method ) {
3590 return true;
3591 }
3592
3593 /**
3594 * Delete a table
3595 * @param string $tableName
3596 * @param string $fName
3597 * @return bool|ResultWrapper
3598 * @since 1.18
3599 */
3600 public function dropTable( $tableName, $fName = __METHOD__ ) {
3601 if ( !$this->tableExists( $tableName, $fName ) ) {
3602 return false;
3603 }
3604 $sql = "DROP TABLE " . $this->tableName( $tableName );
3605 if ( $this->cascadingDeletes() ) {
3606 $sql .= " CASCADE";
3607 }
3608
3609 return $this->query( $sql, $fName );
3610 }
3611
3612 /**
3613 * Get search engine class. All subclasses of this need to implement this
3614 * if they wish to use searching.
3615 *
3616 * @return string
3617 */
3618 public function getSearchEngine() {
3619 return 'SearchEngineDummy';
3620 }
3621
3622 public function getInfinity() {
3623 return 'infinity';
3624 }
3625
3626 public function encodeExpiry( $expiry ) {
3627 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3628 ? $this->getInfinity()
3629 : $this->timestamp( $expiry );
3630 }
3631
3632 public function decodeExpiry( $expiry, $format = TS_MW ) {
3633 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3634 ? 'infinity'
3635 : wfTimestamp( $format, $expiry );
3636 }
3637
3638 public function setBigSelects( $value = true ) {
3639 // no-op
3640 }
3641
3642 public function isReadOnly() {
3643 return ( $this->getReadOnlyReason() !== false );
3644 }
3645
3646 /**
3647 * @return string|bool Reason this DB is read-only or false if it is not
3648 */
3649 protected function getReadOnlyReason() {
3650 $reason = $this->getLBInfo( 'readOnlyReason' );
3651
3652 return is_string( $reason ) ? $reason : false;
3653 }
3654
3655 public function setTableAliases( array $aliases ) {
3656 $this->tableAliases = $aliases;
3657 }
3658
3659 /**
3660 * @since 1.19
3661 * @return string
3662 */
3663 public function __toString() {
3664 return (string)$this->mConn;
3665 }
3666
3667 /**
3668 * Run a few simple sanity checks
3669 */
3670 public function __destruct() {
3671 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3672 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3673 }
3674
3675 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3676 if ( $danglingWriters ) {
3677 $fnames = implode( ', ', $danglingWriters );
3678 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3679 }
3680 }
3681 }
3682
3683 /**
3684 * @since 1.27
3685 */
3686 abstract class Database extends DatabaseBase {
3687 // B/C until nothing type hints for DatabaseBase
3688 // @TODO: finish renaming DatabaseBase => Database
3689 }